package com.orchard.orchardfarmmanagementsystem.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class CustomOffsetDateTimeDeserializer extends StdDeserializer<OffsetDateTime> {

    public CustomOffsetDateTimeDeserializer() {
        this(null);
    }

    public CustomOffsetDateTimeDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public OffsetDateTime deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException {
        String date = p.getText();
        try {
            // 尝试解析带有时区信息的时间字符串
            return OffsetDateTime.parse(date);
        } catch (Exception e) {
            // 如果失败，则假设时间为本地时间并添加默认时区偏移
            LocalDateTime localDateTime = LocalDateTime.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            return localDateTime.atOffset(ZoneOffset.ofHours(+8)); // 默认使用 GMT+8
        }
    }
}